import axios from "@/axios/axios"
import MUTATIONS from "./mutations"
import router from "@/router/router"
import {getSession, setSession} from "@/util/session"

const {MessageBox, Notification} = ELEMENT;

const state = () => {
  return {
    user: getSession('user') || null
  }
}

const getters = {}
const mutations = {
  [MUTATIONS.SET_USER](state, user) {
    state.user = user
    setSession('user', user)
  }
}
const actions = {
  login({commit}, user) {
    return new Promise((resolve, reject) => {
      axios.post('login.php', user).then(({name, token,message}) => {
        if (!name && !token) reject()
        else commit(MUTATIONS.SET_USER, {name, token})
        resolve()
      }).catch(reject)
    })
  },
  exit({commit, state}) {
    MessageBox.confirm('你确定要退出登录吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      commit(MUTATIONS.SET_USER, null)
      Object.keys(state).map(k => sessionStorage.removeItem(k))
      router.push({name: 'login'})
      Notification.success({
        title: 'Tip',
        message: '退出成功!',
        duration: 1000
      })
    })
  }
}


export default {
  state,
  actions,
  getters,
  mutations
}
